import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router'
import imports from '@/http/service/imports'
import {Message} from 'element-ui'
import {removeAllianceId, removerefsToken, removeToken} from "@/utils/auth";

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    bthMenu: [], // 按钮权限
    AsideMenu: [], // 菜单权限
    powerList: [], // 菜单url
    breadList: sessionStorage.breadList ? JSON.parse(sessionStorage.breadList) : [],
    superAdmin: sessionStorage.super_Admin ? JSON.parse(sessionStorage.super_Admin) : '',
    isStoreUser:false,  // 是否是单店   true 是
    customerId:null,  // identity  客服id
    customerName:'',  // 客服名称，用户名
  },
  getters: {},
  mutations: {
    SET_MENUS: (state, params) => {
      state.AsideMenu = params
    },
    SET_BTHMENU: (state, params) => {
      state.bthMenu = params
    },
    SET_POWERLIST: (state, params) => {
      state.powerList = params
    },
    addBread(state, breadList) {
      state.breadList.push(breadList)
      sessionStorage.setItem('breadList', JSON.stringify(state.breadList))
    },
    setBreadList(state, breadList) {
      state.breadList = breadList
      sessionStorage.setItem('breadList', JSON.stringify(breadList))
    },
    /** 超级管理员 */
    SUPERADMIN(state, params) {
      state.superAdmin = params
      sessionStorage.setItem('supportsystem_Admin', JSON.stringify(params))
    },
    SET_ISSTOREUSER: (state, params) => {
      state.isStoreUser = params
    },
    SET_CUSTOMERID: (state, params) => {
      state.customerId = params
    },
    SET_CUSTOMERNAME: (state, params) => {
      state.customerName = params
    },
    
  },
  actions: {
    // 获取菜单
    async getMenus({commit, dispatch, state}) {
      const bthMenu = []
      const powerList = ['/404']
      const data = {authorities: [{id:'-20221228'}]}
      // const data = await imports.LogoService.getMenus({})
      //   //获取的权限=构造数据
      let authorities = data.authorities || []

      let isStoreUser = data?.isStoreUser // 是否是单店   true 是
      commit('SET_ISSTOREUSER', isStoreUser)

      let customerId = data?.identity
      let customerName = data?.name
      commit('SET_CUSTOMERID', customerId)
      commit('SET_CUSTOMERNAME', customerName)
      
      if (authorities[0]?.id === '-20221228') {
        commit('SUPERADMIN', true)
      } else {
        commit('SUPERADMIN', false)
      }
      if ( authorities.length === 0 ) {
        Message.error('请检查权限设置~')
        return
      }
      let ities = authorities.filter(item => item.parentId === 1698||item.parentId === 1708)
      let author = authorities.filter(item => item.parentId !== 1698||item.parentId === 1708)
      ities.map(it => {
        it.children = []
        author.forEach(ie => {
          if (it.id == ie.parentId) {
            it.children.push(ie)
          }
        })
      })
      //项目需要的数据结构 id匹配 title方便阅读
      let menuList= []
      if(isStoreUser){  // 单店
        menuList = [
          
        ]
      }else{  // 连锁
        menuList = [
          {
            id: 1701,
            web_href: "/home",
            web_title: "首页",
            icon: "Group7",
            butList:[
              
            ]
          },
          {
            id: 1703,
            web_href: "/warningcase",
            web_title: "预警方案",
            icon: "Group7",
            butList:[
              
            ]
          }
        ]
      }
     
      const itiesMap = new Map(ities.map((item) => [item.id, item]))
      const itiesSet = new Set(ities.map(item => item.id))

      //过滤没有权限的菜单
      if (!state.superAdmin) menuList = menuList.filter((item) => itiesSet.has(item.id))
      menuList.map(it => {
        const Objct = itiesMap.get(it.id)
        if (Objct) {
          const childrenIds = new Set(Objct.children.map((child) => child.id));
          it.butList = it.butList?.filter((item) => childrenIds.has(item.id)) || []
          it.children = it.children?.filter((item) => childrenIds.has(item.id)) || []
        }
        //菜单权限
        if (it.children?.length > 0) {
          it.children.forEach((item) =>
            powerList.push(it.web_href + item.web_href)
          );
        } else {
          powerList.push(it.web_href);
        }

        if (it.butList?.length > 0) {
          it.butList.forEach((ite) => {
            bthMenu.push(ite.name);
          });
        }

      })

      let asyncRoutes = router.options.routes[1].children
      const menu = await dispatch('hasPermission', {asyncRoutes, bthMenu, powerList})
      menu.forEach(it => powerList.push(it.path))
      commit('SET_MENUS', menuList)
      commit('SET_BTHMENU', bthMenu)
      commit('SET_POWERLIST', powerList)
    },
    /**
     * 通过meta.code判断是否与当前用户权限匹配
     * @param roles
     * @param route
     */
    hasPermission({}, data) {
      const {asyncRoutes, bthMenu,powerList} = data
      return asyncRoutes.filter(route => {
        //隐式路由直接显示
        if (route.meta.requiresAuth && powerList.indexOf(route.meta.requiresPath) !== -1) return true;
        return bthMenu.indexOf(route.name) >= 0
      })
    },
    logoUp() {
      removeToken()
      removerefsToken()
      removeAllianceId()
      localStorage.removeItem('supportsystem_shopName')
      localStorage.removeItem('supportsystem_code')
    }
  },
  modules: {}
})
